package com.shenghua.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.shenghua.utils.beans.Constants;
import com.shenghua.utils.beans.Dto;
import com.shenghua.utils.beans.ErrorCode;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class PicUtil {

	private static Logger logger = LoggerFactory.getLogger(PicUtil.class);

	/**
	 * 数据流复制文件
	 * @param oldFile
	 * @param newFile
	 * @return
	 */
	public boolean copyFile(File oldFile, File newFile) {
		DataInputStream dis  = null;
		DataOutputStream dos = null;
		
		try {
			dis = new DataInputStream(new FileInputStream(oldFile));
			dos = new DataOutputStream(new FileOutputStream(newFile));
			byte[] b = new byte[8194];
			int len = -1;
			while((len = dis.read(b)) != -1){ // 读取原有图片信息
				dos.write(b);	//把图片写到新照片
			}
			logger.info("照片复制成功！");
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally{
			if(dis!=null){
				try {
					dis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(dos!=null){
				try {
					dos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 带缓冲复制照片
	 * @param oldFile
	 * @param newFile
	 * @return
	 */
	public boolean copyImage(File oldFile, File newFile) {
		BufferedInputStream fis = null;
		BufferedOutputStream fos =null;
		
		try {
			fis = new BufferedInputStream(new FileInputStream(oldFile));   //输入
			fos = new BufferedOutputStream(new FileOutputStream(newFile));   //输出
			byte[] buf = new byte[4096];  
			int i;  
			while ((i = fis.read(buf)) != -1) {  
			    fos.write(buf, 0, i);  
			}
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			if(fis != null ) {
				try {
					fis.close();
				} catch (IOException e) {
					logger.info(" 关闭输入流失败 ！");
				}
			}
			
			if(fos != null ) {
				try {
					fos.close();
				} catch (IOException e) {
					logger.info(" 关闭输出流失败 ！");
				}
			}
		}
	}

	/**
	 * 在window环境中上传照片
	 * @param multFile 上传的文件
	 * @param newFileName 要保存的文件名
	 * @param windowsBaseUrl 保存的文件路径
	 * @return
	 */
	public static Dto<String> uploadImageInWindows(MultipartFile multFile,
									String newFileName,
									String windowsBaseUrl) {
		// 返回值
		Dto<String> dto = new Dto();
		
		// 原文件名
		String filename = multFile.getOriginalFilename();
		// 后缀名
		String type = FilenameUtils.getExtension(filename);
		//String type = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
		String str = "";
		if ((type.equalsIgnoreCase("jpg") || type.equalsIgnoreCase("png") 
				|| type.equalsIgnoreCase("gif")) && newFileName.contains(".")) {
			String path = null;
			// 获取windows环境还是其他环境
			Properties properties = System.getProperties();
			String os = properties.getProperty("os.name");
			logger.info("当前运行环境 ：" + os);
			// 根据不同的运行环境上传图片地址不同
			if (os.contains("Windows")) {
				//path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
				//path = path.substring(0, path.indexOf("parent") + 7) + windowsBaseUrl;
				path = windowsBaseUrl;
				logger.info("windows环境上传图片路径：" + path);
				// 文件保存路径
				File file = new File(path);
				// 文件夹是否存在 不存在递归创建
				if (!file.isDirectory()) {
					file.mkdirs();
				}
				try {
					if(path.endsWith(File.separator)){
						str = newFileName;
					} else {
						str = File.separator + newFileName;
					}
					logger.info("上传图片地址：" + newFileName);
					logger.info("上传图片地址：" + new File(file , str).getAbsolutePath());
					multFile.transferTo(new File(file , str));
					logger.info("上传图片地址：" + (newFileName));
					dto.ReturnSuccess(str, ErrorCode.FILE_UPLOAD_SUCCESS);
					return dto;
				} catch (IOException e) {
					e.printStackTrace();
					dto.ReturnFail(null, ErrorCode.FILE_UPLOAD_ERROR);
					return dto;
				}
			} else {
				dto.ReturnFail(null, ErrorCode.FILE_UPLOAD_FIAL);
				return dto;
			}			
		} else {
			logger.info("上传图片格式错误：" + type);
			logger.info("或文件名有误：" + newFileName);
			dto.ReturnFail(null, ErrorCode.FILE_EXTENSION_ERROR);
			return dto;
		}		
	}
	
	/**
	 * 在Linux环境中上传照片
	 * @param multFile 上传的文件
	 * @param newFileName 要保存的文件名
	 * @param linuxBaseUrl 保存的文件路径
	 * @return
	 */
	public static Dto<String> uploadImageInLinux(
			MultipartFile multFile,
			String newFileName,
			String linuxBaseUrl) {
		// 返回值
		Dto<String> dto = new Dto();
		
		// 原文件名
		String filename = multFile.getOriginalFilename();
		// 后缀名
		String type = FilenameUtils.getExtension(filename);
		//String type = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
		String str = "";
		if ((type.equalsIgnoreCase("jpg") || type.equalsIgnoreCase("png") 
				|| type.equalsIgnoreCase("gif")) && newFileName.contains(".")) {
			String path = null;
			// 获取windows环境还是其他环境
			Properties properties = System.getProperties();
			String os = properties.getProperty("os.name");
			logger.info("当前运行环境 ：" + os);
			// 根据不同的运行环境上传图片地址不同
			if (!os.contains("Windows")) {
				path = linuxBaseUrl;
				logger.info("linux环境上传图片路径：" + path);

				// 文件保存路径
				File file = new File(path);
				// 文件夹是否存在 不存在递归创建
				if (!file.isDirectory()) {
					file.mkdirs();
				}
				try {
					if(file.getAbsolutePath().endsWith(File.separator)){
						str = newFileName;
					} else {
						str = "/" + newFileName;
					}
					logger.info("上传图片地址：" + file + "/" + str);
					multFile.transferTo(new File(file + str));
					dto.ReturnSuccess(str, ErrorCode.FILE_UPLOAD_SUCCESS);
					return dto;
				} catch (IOException e) {
					e.printStackTrace();
					dto.ReturnFail(null, ErrorCode.FILE_UPLOAD_ERROR);
					return dto;
				}
			} else {
				dto.ReturnFail(null, ErrorCode.FILE_UPLOAD_FIAL);
				return dto;
			}		
		} else {
			logger.info("上传图片格式错误：" + type);
			logger.info("或文件名有误：" + newFileName);
			dto.ReturnFail(null, ErrorCode.FILE_EXTENSION_ERROR);
			return dto;
		}		
	}

	/**
	 * 生成图片文件名 
	 * 同ImageController的uploadImageThread
	 * @param multFile
	 * @return
	 */
	public static String generateImageFileName(MultipartFile multFile) {
		String filename = "";
		filename = multFile.getOriginalFilename();
		logger.info("文件名："+filename);
		filename = filename.substring(filename.lastIndexOf("/") + 1, filename.length());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmsss");
		filename = MD5Util.e(filename).toUpperCase()+"-"+sdf.format(new Date()) + ".jpg"; // 加密做成文件名
		return filename;
	}

	public static String generateImageFileName1(MultipartFile multFile) {
		String filename = StringUtils.getUUID();
		String ext = FilenameUtils.getExtension(multFile.getOriginalFilename());
		filename = filename + "." + ext; // 加密做成文件名
		return filename;
	}

    public static boolean DeleteImage(String picAddr) {
		boolean result = false;
		if(null != picAddr && !"".equals(picAddr)){
			File file = new File(picAddr);
			if(file.exists()){
				result = file.delete();
			}
		}
		return result;
    }

	public static Dto<String> uploadImage (
			MultipartFile multFile,
			String uploadUrl,
			String baseUrl)  {
		Dto<String> ret = new Dto<>();
		// 根据系统类型不同进行不同的操作
		Properties properties = System.getProperties();
		String os = properties.getProperty("os.name");
		if(os.contains("Windows")) {
			ret = PicUtil.uploadImageInWindows(multFile, uploadUrl, baseUrl);
		} else {
			ret = PicUtil.uploadImageInLinux(multFile, uploadUrl, baseUrl);
		}
		return ret;
	}
}
